package cn.doitedu.hbase.region;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class MergeRegion {

    public static void main(String[] args) throws IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","spark01:2181,spark02:2181,spark03:2181");
        Connection conn = ConnectionFactory.createConnection(conf);

        Admin admin = conn.getAdmin();
        List<RegionInfo> regions = admin.getRegions(TableName.valueOf("t1"));

        Collections.sort(regions, new Comparator<RegionInfo>() {
            @Override
            public int compare(RegionInfo o1, RegionInfo o2) {
                return Bytes.compareTo(o1.getStartKey(),o2.getStartKey());
            }
        });

        RegionInfo pre = null;
        for(int i=0;i<regions.size();i++){
            if(i%2==0){
                pre = regions.get(i);
            }else{
                admin.mergeRegionsAsync(pre.getRegionName(),regions.get(i).getRegionName(),false);
            }
        }


    }
}
